import $ from 'jquery'
import '@/assets/css/article-nav.scss'
import { Fancybox } from "@fancyapps/ui"
import "@fancyapps/ui/dist/fancybox.css"
import hljs from "highlight.js"
import "highlight.js/styles/a11y-light.css"

export default {
  init(options) {
    // 初始化文章页的各种控件 导航栏、回到顶部按钮、代码块高亮等等
    hljs.highlightAll(); // 高亮代码块
    this.initImgGallery();
    this.initNav(options);
  },
  initNav(options) {
    let titles = $(".article-body").find("h2,h3");
    let navMenu = new Array();
    let subNav = new Array();
    titles.each((index, tag) => {
      let title = $(tag).html();
      $(tag).attr('id', 'anchor' + index);
      $(tag).attr('tag', 'anchor');
      if (tag.localName === 'h2') {
        if (navMenu[navMenu.length - 1]) {
          let lastTopNav = navMenu[navMenu.length - 1];
          lastTopNav.children = subNav;
          subNav = new Array();
        }
        navMenu.push({ "id": "anchor" + index, "label": title, "children": [] });
      } else if (tag.localName === 'h3') {
        subNav.push({ "id": "anchor" + index, "label": title });
      }
    });
    if (subNav.length > 0) {
      navMenu[navMenu.length - 1].children = subNav;
    }
    navMenu.forEach((item) => {
      options.navTree.append(item);
    })
    setTimeout(() => {
      options.navTree.setChecked(options.navTree.getNode('anchor1'), true);
    }, 1000);
    // $(window).scroll(function () {
    //   let scrollItems = $("[tag=anchor]");
    //   console.log(scrollItems);
    //   for (let i = scrollItems.length - 1; i >= 0; i--) {
    //     // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
    //     let scroHei = $(window).scrollTop(); //滚动的高度
    //     console.log("w:" + scroHei);
    //     console.log(scrollItems[i].offsetTop);
    //     console.log(scrollItems[i].id);
    //     if (scroHei >= scrollItems[i].offsetTop) {
    //       options.navTree.setChecked(scrollItems[i].id, true, true);
    //     }
    //   }
    // })
  },
  initImgGallery() {
    $('.article-body img').each((index, img) => {
      let src = $(img).attr('src');
      console.log(src);
      let html = `
      <a data-fancybox="gallery" data-src="` + src + `">
        <img src="` + src + `" />
      </a>`;
      $(img).parents('p').html(html);
    })
    Fancybox.bind("[data-fancybox]", {
      Image: {
        zoom: false,
      }
    });
  },
  navAction(data) {
    var $anchor = $('#' + data.id);
    var top = $anchor.offset().top || 0;
    $('html,body').animate({
      'scroll-top': top - 70
    }, 300);
  }
}